<template>
  <el-dialog :append-to-body="true" :visible.sync="dialog" :title.sync="title" width="940px">
    <el-form ref="form" :model="form" :rules="rules" size="small" label-width="115px">
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="计划名称" prop="planName">
            <el-input v-model="form.planName" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="状态" prop="state">
            <el-radio-group v-model="form.state">
              <el-radio v-for="item in dicts" :key="item.id" :label="item.value" :disabled="isView">{{ item.label }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="开始时间" prop="startTime">
            <el-date-picker
              v-model="form.startTime"
              type="date"
              placeholder="请选择"
              :format="'yyyy-MM-dd'"
              :picker-options="startTimeConfig"
              :readonly="isView"
              style="width: 300px;"
              @change="startTimeChange"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="结束时间" prop="endTime">
            <el-date-picker
              v-model="form.endTime"
              style="width: 300px;"
              type="date"
              placeholder="请选择"
              :format="'yyyy-MM-dd'"
              :picker-options="endTimeConfig"
              :readonly="isView"
              @change="endTimeChange"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="巡检对象" prop="objName">
            <el-select
              v-model="form.objId"
              placeholder="巡检对象"
              multiple
              filterable
              style="width: 760px"
              :disabled="isView"
              @change="eqptSelect($event)"
            >
              <el-option
                v-for="(itemobject,index) in inspectionObject"
                :key="index"
                :label="itemobject.eqptcode+'/'+itemobject.eqptname"
                :value="itemobject.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="巡检内容" prop="templateId">
            <el-select
              v-model="form.templateId"
              placeholder="巡检内容"
              class="input_text"
              :disabled="isView"
              @change="templateSelect($event)"
            >
              <el-option v-for="(itemobject,index) in inspectionTemplate" :key="index" :label="itemobject.templateName" :value="itemobject.id" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="巡检工具">
            <el-select
              v-model="form.toolId"
              class="input_text"
              placeholder="巡检工具"
              multiple
              :disabled="isView"
              @change="toolSelect($event)"
            >
              <el-option v-for="(itemobject,index) in toolItem" :key="index" :label="itemobject.label" :value="itemobject.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="巡检周期" prop="periodName">
            <el-select
              v-model="form.periodId"
              filterable
              placeholder="巡检周期"
              class="input_text"
              :disabled="isView"
              @keydown.native="myMoneyKeyDown"
              @keyup.enter.native="onSubmitPeriod"
              @change="periodSelect($event)"
            >
              <el-option v-for="(itemobject,index) in periodItem" :key="index" :label="itemobject.name" :value="itemobject.id" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="巡检要求">
        <el-input v-model="form.planDesc" :rows="5" style="width: 760px;" type="textarea" :readonly="isView" />
      </el-form-item>
      <el-form-item label="服务商" prop="inspectorId">
        <el-select
          v-model="form.inspectorId"
          placeholder="服务商"
          style="width: 760px;"
          :disabled="isView"
          @change="supplierSelect($event)"
        >
          <el-option v-for="(item,index) in serviceproItem" :key="index" :label="item.seproName" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="备注">
            <el-input v-model="form.notes" :rows="5" style="width: 760px;" type="textarea" :readonly="isView" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-show="isAdd===false && isView===true" :gutter="24">
        <el-col :span="12">
          <el-form-item label="录入人" prop="inputOperator">
            <el-input v-model="form.inputOperator" class="input_text" :readonly="isView" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="录入时间" prop="inputTime">
            <el-date-picker
              v-model="form.inputTime"
              style="width: 300px;"
              type="datetime"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="timestamp"
              placeholder="选择日期时间"
              :disabled="isView"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button v-show="isView===false || isAdd===true" type="text" @click="cancel">取消</el-button>
      <el-button v-show="isAdd===false && isView===true" :loading="loading" type="primary" @click="cancel">返回</el-button>
      <el-button v-show="isView===false" :loading="loading" type="primary" @click="doSubmit">确认</el-button>
    </div>
  </el-dialog>
</template>

<script>
import { add, edit } from '@/api/inspectionPlan'
import request from '@/utils/request'
import { validateNumber } from '@/utils/validate'
import { queryEqpt } from '@/api/tEquipment'
import { queryTemplate } from '@/api/inspectionTemplate'
import { get } from '@/api/dictDetail'
export default {
  props: {
    isAdd: {
      type: Boolean,
      required: true
    },
    supThis: {
      type: Object,
      default: null
    },
    isView: {
      type: Boolean,
      required: true
    }
  },
  data() {
    return {
      loading: false,
      dialog: false,
      dicts: [{ id: 1, value: '1', label: '启动' }, { id: 2, value: '0', label: '暂定' }],
      title: '',
      form: {
        id: '',
        planName: '',
        objName: '',
        toolId: '',
        toolName: '',
        templateId: '',
        templateName: '',
        planDesc: '',
        notes: '',
        periodId: '',
        periodName: '',
        inspectorId: '',
        inspectorName: '',
        vehtypeId: '',
        vehTypeName: '',
        startTime: '',
        endTime: '',
        state: '1',
        inputOperator: '',
        inputTime: ''
      },
      inspectionObject: [],
      inspectionTemplate: [],
      serviceproItem: [],
      periodItem: [
        { id: 1, name: '年' },
        { id: 2, name: '半年' },
        { id: 3, name: '季' },
        { id: 4, name: '月' },
        { id: 5, name: '周' }
      ],
      toolItem: [],
      vehtypeItem: [],
      // -----------------
      realTimeInfo: {
        startTime: '',
        endTime: ''
      },
      startTimeConfig: {},
      endTimeConfig: {},
      rules: {
        planName: [{ required: true, trigger: 'blur', message: '计划名称不能为空' }],
        periodName: [{ required: true, trigger: 'blur', message: '计划周期不能为空' }],
        startTime: [{ required: true, trigger: 'blur', message: '开始时间不能为空' }],
        endTime: [{ required: true, trigger: 'blur', message: '结束时间不能为空' }],
        state: [{ required: true, trigger: 'blur', message: '计划状态不能为空' }],
        objName: [{ required: true, trigger: 'blur', message: '巡检对象不能为空' }],
        templateId: [{ required: true, trigger: 'blur', message: '巡检模板不能为空' }],
        inspectorId: [{ required: true, trigger: 'blur', message: '供应商不能为空' }]
      }
    }
  },
  mounted() {
    this.initTimeConfig()
    // this.tServiceproviderInfoAll()
    this.title = this.isAdd ? '新增' : (this.isView === true ? '详情' : '编辑')
  },
  methods: {
    tServiceproviderInfoAll() {
      this.getAllService().then(res => {
        this.serviceproItem = res
      })
    },
    getAllService() {
      return request({
        url: 'api/tServiceproviderInfoAll',
        method: 'get'
      })
    },
    getInpectionTools() {
      get('巡检工具').then(res => {
        this.toolItem = res.content
      })
    },
    // 日期S
    initTimeConfig() {
      const self = this
      // 开始时间配置
      this.startTimeConfig = {
        disabledDate(time) {
          if (self.realTimeInfo.endTime) {
            return time.getTime() > new Date(self.realTimeInfo.endTime).getTime() ||
              (time.getTime() - new Date().getTime()) / 1000 < 3600 * 24 * 7
          }
          return (time.getTime() - new Date().getTime()) / 1000 < 3600 * 24 * 7
        }
      }
      // 结束时间配置
      this.endTimeConfig = {
        disabledDate(time) {
          if (self.realTimeInfo.startTime) {
            return time.getTime() < new Date(self.realTimeInfo.startTime).getTime() ||
              (time.getTime() - new Date().getTime()) / 1000 < 3600 * 24 * 7
          }
          return (time.getTime() - new Date().getTime()) / 1000 < 3600 * 24 * 7
        }
      }
    },
    startTimeChange(val) {
      this.realTimeInfo.startTime = val
    },
    endTimeChange(val) {
      this.realTimeInfo.endTime = val
    },
    // --------------------------
    queryAllEqpt() {
      queryEqpt({ size: 9999, pageNo: 0 }).then(res => {
        this.inspectionObject = res.content
      })
    },
    queryAllTemplate() {
      queryTemplate({ size: 9999, pageNo: 0 }).then(res => {
        this.inspectionTemplate = res.content
      })
    },
    eqptSelect(event) {
      this.form.objName = event.toString()
      var veh = []
      event.forEach((data, index) => {
        for (var i in this.inspectionObject) {
          if (this.inspectionObject[i].id === data) {
            veh.push(this.inspectionObject[i].eqptname)
          }
        }
        this.form.vehTypeName = veh.toString()
      })
    },
    templateSelect(event) {
      // console.log(this.inspectionTemplate)
      for (var index in this.inspectionTemplate) {
        if (this.inspectionTemplate[index].id === event) {
          this.form.templateName = this.inspectionTemplate[index].templateName
        }
      }
    },
    toolSelect(event) {
      this.form.toolName = event.toString()
    },
    supplierSelect(event) {
      for (var index in this.serviceproItem) {
        if (this.serviceproItem[index].id === event) {
          this.form.inspectorName = this.serviceproItem[index].seproName
        }
      }
    },
    periodSelect(event) {
      for (var index in this.periodItem) {
        if (this.periodItem[index].id === event) {
          this.form.periodName = this.periodItem[index].name
        }
      }
    },
    // 获取id值
    getTembyObjectId(id) {
      return request({
        url: 'api/inspectionTemplate/byObjectId/' + id,
        method: 'get'
      })
    },
    onSubmitPeriod(event) {
      const _this = this
      let flag = false
      const label = event.target.value + '天'
      this.periodItem.forEach(item => {
        if (item.id === -1) {
          item.name = label
          flag = true
        }
      })
      if (!flag) {
        _this.periodItem.push({ id: -1, name: label })
      }
      _this.form.periodId = -1
      _this.form.periodName = label
      event.target.blur()
    },
    myMoneyKeyDown(event) {
      validateNumber(event)
    },
    cancel() {
      this.resetForm()
    },
    doSubmit() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.objId = 0
          this.form.toolId = 0
          if (this.isAdd) {
            this.$confirm('系统将在计划开始前7天自动生成巡检任务，计划时间不能再修改，确认增加?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              this.loading = true
              this.doAdd()
            }).catch(err => {
              console.log(err)
              Promise.reject(err)
              this.loading = false
            })
          } else {
            this.loading = true
            this.doEdit()
          }
        }
      })
    },
    doAdd() {
      add(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '添加成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.$parent.$parent.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    doEdit() {
      edit(this.form).then(res => {
        this.resetForm()
        this.$notify({
          title: '修改成功',
          type: 'success',
          duration: 2500
        })
        this.loading = false
        this.supThis.init()
      }).catch(err => {
        this.loading = false
        console.log(err)
      })
    },
    resetForm() {
      this.dialog = false
      // this.$refs['form'].resetFields()
      this.form = {
        id: '',
        planName: '',
        objName: '',
        toolId: '',
        toolName: '',
        templateId: '',
        templateName: '',
        planDesc: '',
        notes: '',
        periodId: '',
        periodName: '',
        inspectorId: '',
        inspectorName: '',
        vehtypeId: '',
        vehTypeName: '',
        startTime: '',
        endTime: '',
        state: '1',
        inputOperator: '',
        inputTime: ''
      }
    }
  }
}
</script>

<style scoped>
.input_text {
  width: 300px;
}
</style>
